package com.design.marketPrj.application.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.design.marketPrj.application.bean.PO.User;
import com.design.marketPrj.application.commons.CodeAndMsgEnum;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController extends BaseController{

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/loginPage")
    public String loginPage(){
        return "login";
    }

    @RequestMapping("/unAuthPage")
    @ResponseBody
    public String unAuthPage(){
        return "您尚未登录!";
    }

    @RequestMapping(value = "/loginVerify")
    @ResponseBody
    public JSONObject login(String username, String password){
        JSONObject jsonObject = new JSONObject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        Subject currentUser = SecurityUtils.getSubject();
        try {
            //主体提交登录请求到SecurityManager
            currentUser.login(token);
            System.out.println("登录成功");
            jsonObject.put("code",200);
            jsonObject.put("url","/product/index");
            jsonObject.put("token",getToken());
            return jsonObject;
        }
        catch (Exception e){
            if(e.getClass()==IncorrectCredentialsException.class){
                jsonObject.put("msg","密码不正确");
            }
            else if(e.getClass()==UnknownAccountException.class){
                jsonObject.put("msg","账号不存在");
            }
            else if(e.getClass() == AuthenticationException.class){
                jsonObject.put("msg","状态不正常");
            }
            token.clear();
            jsonObject.put("code",500);
            return jsonObject;
        }
    }


}
